<template>
  <div class="article-page">
    <nav class="my-nav van-hairline--bottom">
      <a :class="{active: quertParams.sorter === 'weight_desc'}" href="javascript:;"
        @click="changeSorter('weight_desc')">推荐</a>
      <a :class="{active: quertParams.sorter === ''}" href="javascript:;" @click="changeSorter('')">最新</a>
      <div class="logo"><img src="@/assets/logo.png" alt=""></div>
    </nav>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list @load="loadMore" v-model:loading="loading" :finished="finished">
        <article-item v-for="item in list.rows" :key="item.id" :item="item"></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script setup lang="ts">
import type { QuestionList, QuestionParams } from '@/types/data';
import { getArticleList } from '@/api/article'
import ArticleItem from './components/article-item.vue';
import { ref } from 'vue'
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const list = ref<QuestionList>({
  current: 1,
  pageTotal: 10,
  pageSize: 10,
  total: 0,
  rows: []
}) // 声明数据
const quertParams = ref<QuestionParams>({
  current: 1,
  pageSize: 10,
  stem: "",
  keyWord: "",
  sorter: "weight_desc"
})


const loadMore = async () => {
  const { data } = await getArticleList(quertParams.value)
  list.value = { ...data, rows: [...list.value.rows, ...data.rows] }
  loading.value = false // 关闭进度条
  finished.value = quertParams.value.current === list.value.pageTotal
  finished.value || quertParams.value.current++
}

const onRefresh = async () => {
  quertParams.value.current = 1 // 回到第一页
  const { data } = await getArticleList(quertParams.value)
  list.value = data
  refreshing.value = false // 关闭正在加载
}
const changeSorter = (type: "" | "weight_desc") => {
  quertParams.value.sorter = type
  list.value.rows = [] // 先清空数据 否则就会持续加载
  onRefresh() // 重新加载数据

}
</script>
<style lang="less">
.article-page {
  margin-bottom: 50px;
  margin-top: 44px;

  .my-nav {
    height: 44px;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 999;
    background: #fff;
    display: flex;
    align-items: center;

    >a {
      color: #999;
      font-size: 14px;
      line-height: 44px;
      margin-left: 20px;
      position: relative;
      transition: all 0.3s;

      &::after {
        content: '';
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 0;
        width: 0;
        height: 2px;
        background: #222;
        transition: all 0.3s;
      }

      &.active {
        color: #222;

        &::after {
          width: 14px;
        }
      }
    }

    .logo {
      flex: 1;
      display: flex;
      justify-content: flex-end;

      >img {
        width: 64px;
        height: 28px;
        display: block;
        margin-right: 10px;
      }
    }
  }
}
</style>